import { loginService } from '@/api/user';
import { defineStore } from 'pinia';

interface LoginParams {
  username: string;
  password: string;
}

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: sessionStorage.getItem('token') || '',
      roles: [],
      username: '',
      menuList: sessionStorage.getItem('menuList')
        ? JSON.parse(sessionStorage.getItem('menuList')!)
        : [],
    };
  },
  actions: {
    async login(data: LoginParams) {
      try {
        const {
          token,
          menuList,
          user: { username, roles },
        } = await loginService(data);

        // 将数据存储到pinia中
        this.token = token;
        this.roles = roles;
        this.username = username;
        this.menuList = menuList;

        // 将token存储到本地
        sessionStorage.setItem('token', token);
        sessionStorage.setItem('menuList', JSON.stringify(menuList));
      } catch (err) {
        console.log('登录失败', err);
      }
    },
  },
});
